package io.jee.runshan.controller.admin;

import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.medusa.orm.pager.Pager;
import io.jee.runshan.domain.Product;
import io.jee.runshan.service.IProductService;
import io.jee.runshan.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 商品Controller
 * 
 * @author SunX
 *
 */
@Controller
@RequestMapping("/admin/product/")
public class ProductController {

	private static final String LIST = "admin/product/list";
	private static final String ATTR = "admin/product/attribute";
	private static final String REDIRECT_LIST = "redirect:/admin/product/list";

	@Resource
	private IProductService productService;

	/**
	 * 商品列表
	 * 
	 * @param pager
	 * @param product
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView list(Pager<Product> pager, Product product,
			@RequestParam(value = "status", required = true, defaultValue = "-1") Integer status) {
		ConditionGroup group = new ConditionGroup();
		group.and(Condition.onBool("delFlag").eq(false));
		if (!Utils.isNullOrEmpty(product.getProductName())) {
			group.and(Condition.onText("productName").like("%" + product.getProductName() + "%"));
		}
		if (status > -1) {
			group.and(Condition.onNumber("state").eq(status));
		}
		pager = productService.list(pager, group, "DESC", "publishTime");
		return new ModelAndView(LIST).addObject("pager", pager)
				.addObject("product", product)
				.addObject("status", status);
	}

	/**
	 * 编辑商品
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("edit")
	public ModelAndView edit(Integer id) {
		Product product = null;
		if (!Utils.isNullOrEmpty(id)) {
			product = productService.get(id);
		}
		return new ModelAndView(ATTR).addObject("product", product);
	}

	/**
	 * 保存商品
	 * 
	 * @param product
	 * @return
	 */
	@RequestMapping("save")
	public String save(Product product,Model model) {
		String msg = null;
		try {
			if (Utils.isNullOrEmpty(product.getId())) {
				if(Product.STATE_OFF == product.getState()){
					product.setCloseTime(new Date());
				}
				Integer id = (Integer) productService.save(product);
				product.setId(id);
				msg = "新增成功！";
			} else {
				Product serProduct = productService.load(product.getId());
				BeanUtils.copyProperties(product, serProduct,new String[]{"publishTime","closeTime","QRCode","productCode"});
				if(Product.STATE_OFF == product.getState()){
					if(Utils.isNullOrEmpty(serProduct.getCloseTime())){
						serProduct.setCloseTime(new Date());
					}
				}
				productService.update(serProduct);
				msg = "修改成功！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "未知错误！" + e.getMessage();
		}
		model.addAttribute("msg",msg);
		return REDIRECT_LIST;
		/*return new ModelAndView(ATTR).addObject("product", product)
				.addObject("msg", msg);*/
	}
	
	/**
	 * 批量导入
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * 
	 */
	@RequestMapping(value = "import")
	public String importXls(HttpServletRequest request, Model model) throws IOException {
		String tempPath = System.getProperty("java.io.tmpdir")+"/"+System.currentTimeMillis()+"/";
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("file");
		
		File inputZip = new File(tempPath,multipartFile.getOriginalFilename());
		inputZip.mkdirs();
		multipartFile.transferTo(inputZip);
		
		String rootPath = "/upload";
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		String path = rootPath + "/productImg/" + dateformat.format(new Date());//如：/productImg/2015-01-21
		String realPath = request.getSession().getServletContext().getRealPath(path); 
		String contextPath = request.getContextPath();
		productService.importProduct(inputZip, tempPath, path, realPath, contextPath);
		model.addAttribute("success", true);
		return REDIRECT_LIST;
	}

	/**
	 * 删除商品
	 * 
	 * @param product
	 * @return
	 */
	@RequestMapping("delete/{ids}")
	public String delete(@PathVariable Integer[] ids,Model model) {
		String msg = "数据没做任何操作";
		try {
			int count = 0;
			if (ids.length > 0) {
				for (Integer id : ids) {
					productService.update("delFlag", true, id);
					count++;
				}
				msg = count + "条记录删除成功！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "未知错误！" + e.getMessage();
		}
		model.addAttribute("msg",msg);
		return REDIRECT_LIST;
	}
	
	/**
	 * 修改状态
	 * @param id
	 * @return
	 */
	@RequestMapping("/updateState")
	public String updateState(Integer id,Model model) {
		String msg = null;
		try {
			Product product = productService.load(id);
			if (product.getState() == 1) {
				product.setState(0);
				product.setCloseTime(new Date());
				msg = "下架成功！";
			} else {
				product.setState(1);
				product.setCloseTime(null);
				msg = "上架成功！";
			}
			productService.update(product);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "未知错误！" + e.getMessage();
		}
		model.addAttribute("msg",msg);
		return REDIRECT_LIST;
	}
	
	/**
	 * 置顶
	 * @param id
	 * @return
	 */
	@RequestMapping("/onTop")
	public String onTop(Integer id,Model model) {
		String msg = null;
		try {
			productService.update("publishTime", new Date(), id);
			msg = "置顶成功！";
		} catch (Exception e) {
			e.printStackTrace();
			msg = "未知错误！" + e.getMessage();
		}
		model.addAttribute("msg",msg);
		return REDIRECT_LIST;
	}
}
